<?php


namespace app\admin\controller;

use app\admin\model\Courses;
use app\admin\model\Video;
use app\services\Oss;
use OSS\OssClient;
use think\Config;
use think\Controller;
use think\Request;

define('FFMPEG_PATH', '/public/ffmpeg/bin/ffmpeg -i "%s" 2>&1');
class VideoController extends Controller
{


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $videos = Video::paginate(3);
        return view('index',compact('videos'));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        //
        $courses = Courses::all();
        if ($request->isPost()) {
            $data = $request->post();
            if ($data['url'] === ""){
                return $this->error('未上传视频');
            }
            $validate = $this->validate($data, [
                'title|视频标题' => 'require',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            $data['addtime'] = time();
            $video = new Video();
            $res = $video->insert($data);
            if ($res) {
                return $this->success('添加成功', 'index');
            } else {
                return $this->error('添加失败', 'add');
            }
        }
        return view('add',compact('courses'));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request,$id)
    {
        //
        $courses = Courses::all();
        $video = Video::get($id);
        if ($request->isPost()) {
            $data = $request->post();
            if ($data['url'] === ""){
                unset($data['url']);
            }else{
                $old_url = $video->url;
                $old_url = substr($old_url,strripos($old_url,"/")+1);
                $config = Config::get('aliyun_oss');
                Oss::publicDeleteObject($config['Bucket'],$old_url);
            }
            $validate = $this->validate($data, [
                'title|视频标题' => 'require',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            $data['addtime'] = time();
            $res = $video->allowField(true)->save($data);
            if ($res) {
                return $this->success('添加成功', 'index');
            } else {
                return $this->error('添加失败', 'edit');
            }
        }
        return view('edit',compact('courses','video'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    public function upload(Request $request) {
        $file=$request->file('file');
        $config = Config::get('aliyun_oss');

        $video=$file->getRealPath();
        $fileName = $file->getInfo()['name'];
        $fileType = substr($fileName,strripos($fileName,".")+1);
        $key = time() . rand(10000, 99999999).".".$fileType;
//        Oss::createBucket()
        $res = Oss::publicUpload($config['Bucket'], $key,$video,['ContentType' => 'video/'.$fileType]);
        if ($res){
            $url = 'https://'.$config['Bucket'].'.'.$config['Endpoint'].'/'.$key;
            $data['status'] = 1;
            $data['url'] = $url;
        }else{
            $data['status'] = 1;
            $data['url'] = "";
        }
        $data['res'] = $res;
        return json($data);
    }

    public function multiuploadFile() {
        /*
         *
'KeyId'
'KeySecret'
'Endpoint'
'Bucket'
         * */
        $config = Config::get('aliyun_oss');
        new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
    }


    private function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }

    public function callback() {
        // 1.获取OSS的签名header和公钥url header
        $authorizationBase64 = "";
        $pubKeyUrlBase64 = "";
        /*
         * 注意：如果要使用HTTP_AUTHORIZATION头，你需要先在apache或者nginx中设置rewrite，以apache为例，修改
         * 配置文件/etc/httpd/conf/httpd.conf(以你的apache安装路径为准)，在DirectoryIndex index.php这行下面增加以下两行
            RewriteEngine On
            RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
         * */
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
            $authorizationBase64 = $_SERVER['HTTP_AUTHORIZATION'];
        }
        if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL'])) {
            $pubKeyUrlBase64 = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
        }

        if ($authorizationBase64 == '' || $pubKeyUrlBase64 == '') {
            header("http/1.1 403 Forbidden");
            exit();
        }

        // 2.获取OSS的签名
        $authorization = base64_decode($authorizationBase64);

        // 3.获取公钥
        $pubKeyUrl = base64_decode($pubKeyUrlBase64);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pubKeyUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $pubKey = curl_exec($ch);
        if ($pubKey == "") {
            //header("http/1.1 403 Forbidden");
            exit();
        }

        // 4.获取回调body
        $body = file_get_contents('php://input');

        // 5.拼接待签名字符串
        $authStr = '';
        $path = $_SERVER['REQUEST_URI'];
        $pos = strpos($path, '?');
        if ($pos === false) {
            $authStr = urldecode($path)."\n".$body;
        } else {
            $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
        }

        // 6.验证签名
        $ok = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
        if ($ok == 1) {
            header("Content-Type: application/json");
            $data = array("Status"=>"Ok");
        } else {
            //header("http/1.1 403 Forbidden");
            $data = array("Status"=>"error");
        }
        return json_encode($data);
    }
    public function getSign() {
        $config = Config::get('aliyun_oss');
        $id= $config['KeyId'];          // 请填写您的AccessKeyId。
        $key= $config['KeySecret'];     // 请填写您的AccessKeySecret。
        // $host的格式为 bucketname.endpoint，请替换为您的真实信息。
//        $host = 'http://bucket-name.oss-cn-hangzhou.aliyuncs.com';
        $host = "http://{$config['Bucket']}.{$config['Endpoint']}";
        // $callbackUrl为上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实URL信息。
        $callbackUrl = input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME').'/'.url('/admin/video/callback');
        $dir = 'videos/';          // 用户上传文件时指定的前缀。

        $callback_param = array('callbackUrl'=>$callbackUrl,
                     'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
                     'callbackBodyType'=>"application/x-www-form-urlencoded");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);

        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition;

        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start;

        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
        return json_encode($response);
    }

}




